package com.example.su_shi_tan_core

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.alibaba.fastjson.JSON
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import com.example.su_shi_tan_bas_lib.utils.even.TO_REFRESH_USER_INFO
import com.example.su_shi_tan_bas_lib.utils.even.TO_REFRESH_USER_SIGN_USER_INFO
import com.example.su_shi_tan_core.bean.SignUserBean
import com.example.su_shi_tan_core.constant.SignUserBeanHolder
import com.example.su_shi_tan_core.db.LogInTokenManager
import com.example.su_shi_tan_core.db.UserInfoBeanHolder
import org.greenrobot.eventbus.EventBus

class SignUserWorker(context: Context, param: WorkerParameters) : Worker(context, param) {
    override fun doWork(): Result {

        if (!LogInTokenManager.tokenManager.haveSignedIn()) return Result.success()

        RestClient.builder()
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "sign" to "1",
                        "integral" to "1",
                        "all" to "1"
                    )
                )
            )
            .url(R.string.sign_user)
            .success {
                parseSignUser(it)
            }.build().post()

        return Result.success()
    }

    private fun parseSignUser(it: String?) {
        val obj = JSON.parseObject(it, SignUserBean::class.java)
        SignUserBeanHolder.onSave(obj)

        EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_SIGN_USER_INFO))
    }
}